package com.app.extended_plugin;

import android.app.Activity;
import android.util.Log;
import android.view.ViewTreeObserver;

import com.app.extended_plugin.utlis.KeyBoardUtils;

import io.flutter.plugin.common.EventChannel;

public /**
 * 键盘事件类
 */
class KeyboardEventHandler implements  EventChannel.StreamHandler {
    public static final int keyboardIsHide = 0;
    public static final int keyboardIsShow = 1;
    ViewTreeObserver.OnGlobalLayoutListener listener;
    private Activity activity;
    private EventChannel.EventSink eventSink;
    private static final String TAG = "KeyboardEventHandler";

    public KeyboardEventHandler(Activity activity) {


        this.activity = activity;
        onAttachedActivity();
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        Log.e(TAG, "onListen: ");
        this.eventSink = eventSink;

    }

    @Override
    public void onCancel(Object o) {
        Log.e(TAG, "onCancel: ");
        this.eventSink = null;
    }

    private void onAttachedActivity(){
        Log.i(TAG, "onAttachedToActivity:a "+Thread.currentThread().getName());

        listener = KeyBoardUtils.doMonitorSoftKeyWord(activity.getWindow().getDecorView().getRootView(), new KeyBoardUtils.OnSoftKeyWordShowListener() {
            @Override
            public void hasShow(boolean isShow) {
                if(eventSink!=null){
                    eventSink.success(isShow?keyboardIsShow:keyboardIsHide);
                }
            }
        });
    }

    private void onDetachedActivity(){
        KeyBoardUtils.removeKeyWordListener(activity.getWindow().getDecorView().getRootView(),listener);
        activity = null;
    }
}
